package com.szyt.basicframe.controller;

import com.szyt.basicframe.common.ResponseResult;
import com.szyt.basicframe.common.StatusEnum;
import com.szyt.basicframe.pojo.bo.LoginUser;
import com.szyt.basicframe.pojo.request.UserLoginRequest;
import com.szyt.basicframe.service.ICaptchaService;
import com.szyt.basicframe.service.ILoginService;
import com.szyt.basicframe.util.LoginUtil;
import com.szyt.basicframe.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/login")
@Slf4j
@Api(tags = "登录")
public class LoginController {
    @Autowired
    ILoginService loginService;

    @Autowired
    private ICaptchaService captchaService;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    @ApiOperation("登录")
    public ResponseResult login(@RequestBody UserLoginRequest user, HttpServletRequest request) {
        // 获取会话ID
        String sessionId = request.getSession().getId();

        // 验证验证码
        if (!captchaService.validateCaptcha(sessionId, user.getCaptcha())) {
            return ResponseResult.error(StatusEnum.VERIFICATION_CODE_EXPIRE);
        }
        //验证用户
        return loginService.login(user);
    }

    @GetMapping("/logout")
    @ApiOperation("退出登录")
    public ResponseResult logout() {
        // 获取SecurityContextHolder中userId
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        // 删除缓存用户信息
        redisUtil.del(LoginUtil.getUserCacheKey(userId));
        return ResponseResult.success("注销成功", null);
    }
}
